﻿using System;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
using WebDemo.Models;

namespace WebDemo.Helpers
{
    /// <summary>
    /// 枚举转换器
    /// </summary>
    public class EnumToStringConverter : JsonConverter<KFDocumentStatus>
    {
        public override KFDocumentStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var description = reader.GetString();
            foreach (var field in typeof(KFDocumentStatus).GetFields())
            {
                if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
                {
                    if (attribute.Description == description || field.Name == description)
                    {
                        return (KFDocumentStatus)field.GetValue(null);
                    }
                }
                else
                {
                    if (field.Name == description)
                    {
                        return (KFDocumentStatus)field.GetValue(null);
                    }
                }
            }
            throw new ArgumentException($"无法将'{description}'转换为{typeof(KFDocumentStatus)}");
        }

        public override void Write(Utf8JsonWriter writer, KFDocumentStatus value, JsonSerializerOptions options)
        {
            // 通过反射获取枚举的Description特性
            var description = value.GetDescription();
            writer.WriteStringValue(description);
        }
    }
}
